/*
 * if client is wechat and has no localStorage of totem_mall_uid
 * we will call force it to get wechat oauth
 */
//(async function( window, undefined ) {
(function( window, undefined ) {

    const totemUID = localStorage.getItem('totemUID');
    if (totemUID) {
        //如果已存在，纪录个数据直接返回
        const today = new Date().toISOString().split('T')[0]; // 获取今天的日期，格式为 YYYY-MM-DD
        const lastOpenDate = localStorage.getItem('lastOpenDate'); // 获取上次打开应用的日期
        let alertMessage = false; // 初始设置为不提示消息
        //if (lastOpenDate !== today) { // 如果上次打开的日期不是今天，则认为是今天第一次打开
        if (!lastOpenDate) { // 如果已经提示过
            alertMessage = true;
            localStorage.setItem('lastOpenDate', today); // 更新上次打开的日期为今天
        }
        // 如果是今天第一次打开，则显示提示消息
        if (alertMessage&&false) {
            alert('欢迎来到二代菌及微生态医学前沿！分享本内容给朋友阅读可获得更多健康金豆哦！');
            if (totemUID=='1') alert(window.location.href);
        }
        const response = fetch('/apps/wx-client-hook', { method: 'POST', headers: { 'Content-Type': 'application/json', },
            body: JSON.stringify({ totemUID, href: window.location.href, memo: 'totemUID existed in localStorage' }),
        });
        return;
    }

    const params = new URLSearchParams(location.search);

    const ua = navigator.userAgent;
    if (ua.indexOf("MicroMessenger") !== -1 && ua.indexOf('wxwork') == -1 ) {

        let link = location.href;
        let rft = params.get('rft') || 666; //例如小程序中转发webview时、ghost blog中转发，rft可以作为给ghost blog打localStroage时候，构造rid的来源
        let rid = params.get('rid') || rft;
        let encodedLink = encodeURIComponent(link);

        const memo = `params: rft ${params.get('rft')} | rid ${params.get('rid')} | final ${rid}`;
        const response = fetch('/apps/wx-client-hook', { method: 'POST', headers: { 'Content-Type': 'application/json', },
            body: JSON.stringify({ totemUID: 0, href: window.location.href, memo }),
        });

        function generateUUID() {
            const currentDate = new Date();
            const year = currentDate.getFullYear();
            const month = String(currentDate.getMonth() + 1).padStart(2, '0');
            const day = String(currentDate.getDate()).padStart(2, '0');
            const randomPart = Math.random().toString().substr(2, 9);
            return `IWTA-${year}${month}${day}-${randomPart}`;
        }

        let iwtaUUID = localStorage.getItem('iwtaUUID');
        if (!iwtaUUID) {
            iwtaUUID = generateUUID();
            localStorage.setItem('iwtaUUID', iwtaUUID);
        }

        //必须同源，否则授权会出问题
        const url =  `/apps/refer?rid=${rid}&dest=${encodedLink}&iwtaUUID=${iwtaUUID}`;
        location.href =  url;

    }

})( window );
